package com.news_back.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.news_back.common.JwtUtil;
import com.news_back.entity.User;
import com.news_back.mapper.UserMapper;
import com.news_back.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yg
 * @since 2024-03-02
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private JwtUtil jwtUtil;
    @Override
    public Map<String, Object> login(User user) {
        //根据用户名查询
        LambdaQueryWrapper<User> userwrapper = new LambdaQueryWrapper<>();
        //结果不为空，并且密码和传入密码匹配，则生成token，并将用户存入Redis
        userwrapper.eq(User::getUsername, user.getUsername());
        User loginUser = this.baseMapper.selectOne(userwrapper);
        if (loginUser != null && passwordEncoder.matches(user.getPassword(),loginUser.getPassword())){
            //暂时使用UUID，总计方案是jwt
            //String key ="user:"+ UUID.randomUUID();
            //存入Redis
            //redisTemplate.opsForValue().set(key, loginUser,30, TimeUnit.MINUTES);

            //创建jwt
            loginUser.setPassword(null);
            String token = jwtUtil.createToken(loginUser);

            //返回数据
            Map<String,Object> data = new HashMap<>();
            data.put("token",token);
            return data;

        }
        return null;
    }
}
